<template>
  <div class='page grey-stage home'>
    <top-filter v-show="!isShowSearch" :filterOptions="filterOptions" @load-more="loadFilter"
                :activeItem="filterActiveItem" @change-filter="changeFilterValue" @item-selected="topFilterItemSelected"
                :cancelSelect="cancelSelect" ref="topFilter"></top-filter>
    <div class="home-container" ref="container"
         :style="'padding-top:' + this.scrollerTop + 'px; height:' + this.scrollerHeight + 'px'"
         @scroll="onScroll($event)">
      <div v-if="orderListShow">

        <div class="rela-tip-main">
          <div class="rela-result-tip top-list-counter">总计{{ total }}条记录</div>
        </div>
        <div class="order-card" v-for="item in data">
          <div class="order-list">
            <div class="title">
              <span>{{ item.is_new ? '首次签约' : '续报签约'}}</span>
              <span v-if="item.status === 'OK##'" @click="cancel(item.order_sn)"><a>撤消</a></span>
            </div>
            <div class="content">
              <div v-if="item.baby_name">
                <span>宝宝姓名:</span>
                <span>{{ item.baby_name }}</span>
              </div>
              <div v-if="item.parent_name">
                <span>家长姓名:</span>
                <span>{{ item.parent_name }}</span>
              </div>
              <div v-if="item.mobile_num">
                <span>家长手机:</span>
                <span>{{ item.mobile_num }}</span>
              </div>
              <div v-if="item.assist_name">
                <span>顾问:</span>
                <span>{{ item.assist_name }}</span>
              </div>
              <div v-if="item.contract_money">
                <span>签约金额:</span>
                <span>{{ item.contract_money | formatPrice}}</span>
              </div>
              <div v-if="item.contract_number">
                <span>合同编号:</span>
                <span>{{ item.contract_number }}</span>
              </div>
              <div v-if="item.status">
                <span>签约状态:</span>
                <span>{{ item.status === 'DEL#' ? '已撤消' : '已签约' }}</span>
              </div>
              <div v-if="item.pay_time">
                <span>签约时间:</span>
                <span>{{ item.pay_time }}</span>
              </div>
            </div>
          </div>
        </div>
        <!--</scroller>-->
      </div>
      <div v-else>
        <div class="rela-tip-main">
          <div class="rela-result-tip top-list-counter">总计{{ total }}条记录</div>
        </div>

        <load-more :show-loading="loadMoreShow" :tip="loadMoreText" background-color="#fbf9fe"></load-more>
      </div>
      <div>
        <confirm
          v-model="cancelConfirmShow"
          :close-on-confirm="false"
          title="操作提示"
          @on-confirm="onConfirm">
          <p style="text-align:center;">确认撤消?</p>
        </confirm>
      </div>
    </div>
    <crm-cover v-if="isShowCover" :hideCoverOnClick="true"></crm-cover>
    <crm-tabbar activeItem='workbench' ref="tabbar"></crm-tabbar>
  </div>
</template>
<script>
  import {loadTeamSettings, loadMemberSettings, loadFilterFunc} from '../lib/filter'
  import {LoadMore, Confirm} from 'vux'
  import crmTabbar from '../components/crm-tabbar'
  import salesTarget from '../components/sales-target'
  import salesPerformance from '../components/sales-performance'
  import salesExecutive from '../components/sales-executive'
  //  import FunnelModel from '../components/funnel-model'
  import topFilter from '../components/top-filter'
  import crmCover from '../components/crm-cover'
  // import Scroller from 'vue-scroller'
  import store from '../store'
  import {mapState} from 'vuex'

  export default {
    data () {
      let overHeight = document.body.scrollHeight + 22
      return {
        containerHeight: 'height:' + overHeight + 'px;',
        orderListShow: false,
        loadMoreShow: true,
        loadMoreText: '正在加载',
        noDataText: "",
        page_index: 1,
        page_size: 10,
        last_page: 0,
        total: 0,
        cancelConfirmShow: false,
        loading_show: false,
        order_sn: "",
        data: {},
        scrollerHeight: '',
        scrollerTop: '',
        isShowSearch: false,
        cancelSelect: null,
        filterActiveItem: {},
        filterData: {},
        submitData: {},
        calendar: parseInt(this.$route.query.container),
        type: 3,//2负责人 3所属团队
        filterOptions: [
          {
            title: '本月',
            class: 'txt-center',
            value: '4',
            name: 'insert_time',
            checked: '4',
            options: [
              {
                text: '今年',
                value: '0'
              },
              {
                text: '去年',
                value: '1'
              },
              {
                text: '本季度',
                value: '2'
              },
              {
                text: '上季度',
                value: '3'
              },
              {
                text: '本月',
                value: '4'
              },
              {
                text: '上月',
                value: '5'
              },
              {
                text: '本周',
                value: '6'
              },
              {
                text: '上周',
                value: '7'
              },
              {
                text: '今天',
                value: '8'
              },
              {
                text: '昨天',
                value: '9'
              }
            ]
          },
          {
            checked: "3",
            class: "txt-center",
            name: "filter",
            options: [],
            title: "筛选",
            value: "6"
          }
        ]
      }
    },
    components: {
      crmTabbar,
      salesTarget,
      salesPerformance,
      salesExecutive,
      topFilter,
      crmCover,
      LoadMore,
      Confirm
    },
    mounted () {
      this.filterOptions[0].title = this.filterOptions[0].options[parseInt(this.$route.query.calendar)].text
      this.filterOptions[0].checked = this.$route.query.calendar
      this.caculateScroller()
      loadTeamSettings().then((options) => {
        if (options === false) {
          this.filterTeamIndex = 0
          return
        }
        if(this.user.is_team_manager !== 1 && this.user.is_system_manager !== 1){

          return
        }

        if(options[0][1].options[2].options[0].value === '-1'){
          options[0][1].options[2].options.splice(0,1)
        }
        options[0][1].options[2].checked = parseInt(this.$route.query.team_id)

        this.filterOptions[1].options.push(options[0][1].options[2])

      })
      setTimeout(() => {

        loadMemberSettings().then((options) => {

          if (options === false) {
            this.filterMemberIndex = 0
            return
          }

          options[0][1].options[1].show = true

          if(options[0][1].options[1].options[0].value === '-1'){
            options[0][1].options[1].options.splice(0,1)
            options[0][1].options[1].checked = options[0][1].options[1].options[0].value

          }

          if(this.user.is_team_manager === 1 || this.user.is_system_manager === 1){
            this.filterOptions[1].options.push(options[0][1].options[1])

          }else{

            for (let i = options[0][1].options[1].options.length - 1; i >= 0; i--) {
              if (options[0][1].options[1].options[i].value !== this.user.id) {
                options[0][1].options[1].options.splice(i, 1);
              }
            }
            options[0][1].options[1].checked = options[0][1].options[1].options[0].value
            this.filterOptions[1].options.push(options[0][1].options[1])
            this.filterOptions[1].checked = '2'
//            this.type = 2
//            this.filterOptions[1].value = 0
//            console.log()
          }


          this.getOrders(this.$route.query.calendar,this.type)


        })
      })



    },
    filters: {
      formatPrice: function (value) {
        return (value / 100).toFixed(2)
      }
    },
    methods: {
      refresh (iscroll) {
        console.log('refresh')
        this.page_index = 1
        this.getOrders();
      },
      load (iscroll) {
        console.log('load')
        if (this.last_page > this.page_index) {
          this.page_index++
          this.getOrders();
        } else {
          this.noDataText = "没有更多数据"
          this.$refs.my_scroller.finishInfinite(true);
          this.$refs.my_scroller.finishPullToRefresh();
        }
      },
      onScroll(event){
        let offsetHeight = event.currentTarget.offsetHeight
        let scrollHeight = event.target.scrollHeight
        let scrollTop = event.target.scrollTop
        if (offsetHeight + scrollTop === scrollHeight && this.loading_show === false) {
          this.loading_show = true;
          if (this.last_page > this.page_index) {
            this.page_index++
            this.getOrders();
          }
        }
      },
      cancel(order_sn){
        this.cancelConfirmShow = true
        this.order_sn = order_sn
      },
      onConfirm(){
        if (this.order_sn) {
          this.saveOrderStatus(this.order_sn)
        }
      },
      caculateScroller () {
        const winHeight = window.innerHeight
        const filterHeight = this.$refs['topFilter'].$el.offsetHeight
        const tabbarHeight = this.$refs['tabbar'].$el.offsetHeight
        this.scrollerTop = filterHeight
        this.scrollerHeight = winHeight - filterHeight - tabbarHeight
      },
      loadFilter: loadFilterFunc,
      topFilterItemSelected (item, index) {
        console.log('topFilterItemSelected')
        if (typeof item.name !== 'undefined' && item.name === 'search') {
          this.isShowSearch = !this.isShowSearch // 搜索栏打开
          this.cancelSelect = null
        } else {
          this.isShowSearch = false // 打开的是筛选栏
        }

//        if (this.isShowSearch === false) {
//          if (this.isShowSearch === false) {
//            this.keyword = ''
////            this.emptyCustoms()
////            this.getCustoms()
//          }
//        }
      },
      changeFilterValue (filterOptions) {
        filterOptions[0].options.forEach((range) => {
          if (this.filterOptions[0].checked === range.value) {
            this.filterOptions[0].title = range.text
          }
        })

        this.getOrders()
      },

      saveOrderStatus(order_sn) {
        this.cancelConfirmShow = false
        this.$vux.loading.show({text: '进行中'})
        store.dispatch('saveOrderStatus', order_sn).then((response) => {
          if (response.data.errcode === 0) {
            this.$vux.loading.hide()
            this.page_index = 1
            this.getOrders()
          } else {
            this.$vux.loading.hide()
          }
        }).catch((error) => {
          console.log(error)
          this.$vux.loading.hide()
        })
      },

      getOrders (calendar, type) {
        this.total = 0
        this.loadMoreText = "正在加载"
        this.loadMoreShow = true
        if (!calendar) calendar = this.filterOptions[0].checked
        type = this.filterOptions[1].checked
        var that = this
        let params = ''
        // 获取工作台信息
        if (type === '2') {
          params = {calendar}
          if(this.user.is_team_manager !== 1 && this.user.is_system_manager !== 1) {
            if(this.filterOptions[1].options[0].checked !== '-1'){
              params.suid = this.filterOptions[1].options[0].checked
            }
          }else{
            if(this.filterOptions[1].options[1].checked !== '-1'){
              params.suid = this.filterOptions[1].options[1].checked
            }
          }


        } else {
          params = {calendar}
          console.log(this.filterOptions[1].options)
          if (this.filterOptions[1].options[0].checked !== '-1') {
            params.team_id = this.filterOptions[1].options[0].checked
          }
        }

        params.page_index = that.page_index
        params.page_size = that.page_size

        this.calendar = calendar
        // 获取工作台信息
        store.dispatch('getOrders', params).then((response) => {
          if (response.data.errcode === 0) {
            let res = response.data.results.data
            if (res.length > 0) {
              that.last_page = response.data.results.last_page
              that.orderListShow = true
              that.total = response.data.results.total
              if (that.page_index > 1) {
                for (let item in res) {
                  that.data.push(res[item])
                }
              } else {
                that.data = res
              }
              that.loading_show = false

            } else {
              that.orderListShow = false
              that.loadMoreText = "暂无数据"
              that.loadMoreShow = false
              that.loading_show = false
            }
          } else {
            console.debug('系统出错请联系管理员!', JSON.stringify(response.data))
          }
          setTimeout(() => {
            if (that.$refs.my_scroller) {
              that.$refs.my_scroller.finishInfinite(true);
//              that.$refs.my_scroller.finishPullToRefresh();
              setTimeout(() => {
                that.$refs.my_scroller.resize();
              })
            }
          }, 1500)

        }).catch(() => {
          this.loading_show = false
        })
      },

    },
    watch: {
      filterOptions () {

      },

    },
    computed: {
      ...mapState({
        isShowCover: state => state.app.isShowCover,
        totalTarget: state => state.app.target,
        user: state => state.app.user,
      })
    }
  }
</script>
<style lang="less">

  @import "../less/base";

  section {
    background-color: white;
  }

  .home-container {
    overflow-x: hidden;
    overflow-y: auto;
    /*-webkit-overflow-scrolling: touch;*/
  }

  .order-card {
    background-color: white;
    margin-bottom: 10px;
  }

  .order-list {
    /*margin: 10px 10px;*/
    margin-left: 10px;
    margin-right: 10px;
    padding-bottom: 5px;
    padding-top: 5px;

    .title {
      font-size: 16px;
      padding-bottom: 5px;
      span:nth-child(2) {
        float: right;
        a {
          color: #20a0ff;
        }
      }
    }
    .content {
      font-size: 14px;
    }
  }

</style>
